import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { Route } from '@/models/connect';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */
export const getAuthorityFromRouter = <T extends { path?: string }>(
  router: T[] = [],
  pathname: string,
): T | undefined => {
  const authority = router.find(({ path }) => path && pathRegexp(path).exec(pathname));
  if (authority) return authority;
  return undefined;
};

export const getRouteAuthority = (path: string, routeData: Route[]) => {
  let authorities: string[] | string | undefined;
  routeData.forEach(route => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

// 判断对象是否为空
const isEmpty = (object: Object) => {
  for (const name in object) {
    if (Object.prototype.hasOwnProperty.call(object, name)) {
      return false;
    }
  }
  return true;
};

// 去掉空对象
export const removeEmptyProperty = (object: Object) => {
  for (const i in object) {
    if (Object.prototype.hasOwnProperty.call(object, i)) {
      const value = object[i];
      if (typeof value === 'object') {
        if (Array.isArray(value)) {
          if (value.length === 0) {
            delete object[i];
            continue;
          }
        }
        removeEmptyProperty(value);
        if (isEmpty(value)) {
          delete object[i];
        }
      } else if (value === '' || value === null || value === undefined || value === 'undefined') {
        delete object[i];
      }
    }
  }
};

export const setPropertyUndefinedIfEmpty = (object: Object) => {
  if (object) {
    for (const key of Object.keys(object)) {
      if (object[key] === '') {
        object[key] = undefined;
      }
    }
    return object;
  }
  return undefined;
};
